var Hzh = {};
var file_grid = $('#file_grid');
file.initFile = function(){
	
	//----------------------------------时间格式化------------------------------------------------
	Date.prototype.format = function (format) {  
	    var o = {  
	        "M+": this.getMonth() + 1,  
	        "d+": this.getDate(),  
	        "h+": this.getHours(),   
	        "m+": this.getMinutes(),  
	        "s+": this.getSeconds(),  
	        "q+": Math.floor((this.getMonth() + 3) / 3), 
	        "S": this.getMilliseconds()  
	    }  
	    if (/(y+)/.test(format))  
	        format = format.replace(RegExp.$1, (this.getFullYear() + "")  
	            .substr(4 - RegExp.$1.length));  
	    for (var k in o)  
	        if (new RegExp("(" + k + ")").test(format))  
	            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));  
	    return format;  
	}
	   
	Hzh.formatToDateTime = function(value) {
		if (value == null || value == '') {
			return '';
		}
		var dt;
		if (value instanceof Date) {
			dt = value;
		} else {
			dt = new Date(value);
			
		}
		return dt.format("yyyy-MM-dd hh:mm:ss");
	};
	
	file_grid.datagrid({
    	onLoadSuccess : function(){
    		$(".downloadFile").linkbutton({plain:true, iconCls:"icon-download" });
    		$(".deleteFile").linkbutton({plain:true, iconCls:"icon-delete" });
    		file_grid.datagrid('fixRowHeight'); 
    		if(userRole == "teacher"){
    			file_grid.datagrid('hideColumn','operatorDownload');
    		}
    		if(userRole == "student"){
    			file_grid.datagrid('hideColumn','operatorDelete');
    		}
    	}
    });
	
	//----------------------------------查询-----------------------------------------------------
	
	//按照姓名、性别、角色、类型进行精确查询
	$("#file_toolbar [tag='query']").click(function(){
		 file_grid.datagrid('load',{
			 fileName: $("[name='searchFileName']").val(),
			 uploadTeacher: $("[name='searchTeacherName']").val(),
			 fileDescription: $("[name='searchFileDescription']").val(),
			 startTime : $("[name='startTime']").val(),
			 endTime : $("[name='endTime']").val()
		 });
	});
	
	//----------------------------------清空-----------------------------------------------------
	$("#file_toolbar [tag='clear']").click(function(){
		//清空表单中的资源
		$('input').val("");
		file_grid.datagrid("load",{});
	});
	
	//----------------------------------批量删除-----------------------------------------------------
	$("#file_toolbar [tag='deleteBatch']").click(function(){
        var selectedRows = file_grid.datagrid("getSelections");
        if (selectedRows.length == 0) {
            $.messager.alert("提示", "请选择要删除的数据！","warning");
            return;
        }
        var fileIdArray = [];
        for ( var i = 0; i < selectedRows.length; i++) {
        	fileIdArray.push(selectedRows[i].fileId);
        }
        var fileIds = fileIdArray.join(",");
        $.messager.confirm("提示", "您确定要删除这<font color=red>" + selectedRows.length + "</font>条数据吗？", function(r) {
            if (r) {
            	$.getJSON(G_CTX_PATH+"/view/delete",{fileIds:fileIds},function(data){
    				if (data.success) {
    					$.messager.alert("提示","删除成功!","info");							
    					file_grid.datagrid("reload");
    				} else {
    					$.messager.alert("提示","删除失败!",data.errorMsg);
    				}
    			});
            }
        });
	});
	
	//----------------------------------上传-----------------------------------------------------
	$("#file_toolbar [tag='upload']").click(function(){

	    // 验证表单
        if(!$('#fileNameTemp').val()) {
        	$.messager.alert("提示","请选择要上传的资源！","warning");
        	return;
        }
        if(!$('#fileDescriptionTemp').val()) {
        	$.messager.alert("提示","请填写上传资源描述！","warning");
        	return;
        }

        $.messager.confirm("提示", "确认上传资源吗?", function(r){
            if (r){
                $.messager.progress({
                    title:"稍等",
                    msg:"正在上传..."
                });

                var param = $("#uploadForm").serialize();
                var url = G_CTX_PATH + "/view/create?"+param;
                
                $.ajaxFileUpload({
                    url : url,
                    type : 'POST',
                    fileElementId : 'fileNameTemp', 
                    dataType : 'text',
                    success : function(result) {
                        $.messager.progress("close");
                        if (result == "success") {
                        	$('#fileNameTemp').val('');
                        	$('#fileDescriptionTemp').val('');
                        	file_grid.datagrid('reload');
                        } else {
                        	$.messager.alert("提示","上传失败！","warning");
                        }
                    },
                    error : function(data, status, e) {
                        $.messager.progress("close");
                        $.messager.alert("提示", '出错了',"error");
                    }
                });
            }
        });
	});
}

file.operatorDownload = function(value, row, index) {
	return '<a class="downloadFile" href="javascript:file.downloadFile(\''+row.fileId+'\')" >下载</a>';
};

file.operatorDelete = function(value, row, index) {
	return '<a class="deleteFile" href="javascript:file.deleteFile(\''+row.fileId+'\')" >删除</a>';
};

file.downloadFile = function(fileId){
	file_grid.datagrid("clearSelections");
	var url=G_CTX_PATH + '/view/downloadFile/'+fileId;
	window.open(url);
}

file.deleteFile = function(fileId){
	file_grid.datagrid("clearSelections");
	$.messager.confirm("删除确认", "确认删除此条数据?", function(r){
		if (r){
			$.getJSON(G_CTX_PATH+"/view/delete",{fileId:fileId},function(data){
				if (data.success) {
					$.messager.alert("提示","删除成功!","info");
					file_grid.datagrid("reload");
				} else {
					$.messager.alert("提示","删除失败!",data.errorMsg);
				}
			});
		}
	});
}

file.initFile();